package com.apex.memotouch;

/**
 * <p>Copyright © 2016年 珠海艾派克科技股份有限公司. All rights reserved.
 *
 *@author Simon
 */

import android.app.ProgressDialog;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.apex.iot.card.Card;
import com.apex.iot.card.CardEvent;
import com.apex.iot.card.CardFile;
import com.apex.iot.card.CardFileReadEvent;
import com.apex.iot.card.CardFileReadListener;
import com.apex.iot.card.CardFileReader;
import com.apex.iot.card.CardFileWriteEvent;
import com.apex.iot.card.CardFileWriteListener;
import com.apex.iot.card.CardFileWriter;
import com.apex.iot.card.CardListener;
import com.apex.iot.card.Device;
import com.apex.iot.card.LockException;
import com.apex.iot.card.ModeException;
import com.apex.iot.card.PackFormatException;
import com.apex.iot.card.UnauthorizedException;
import com.apex.iot.card.adapter.Adapter;
import com.apex.iot.card.adapter.AdapterDevice;
import com.apex.iot.card.adapter.AdapterEvent;
import com.apex.iot.card.adapter.AdapterException;
import com.apex.iot.card.adapter.AdapterListener;
import com.apex.iot.card.nfc.NFCDevice;
import com.apex.memotouch.utils.DeviceManager;
import com.apex.memotouch.utils.DeviceUtils;
import com.apex.memotouch.utils.FileManager;
import com.apex.memotouch.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseNFCActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private String TAG = "MainActivity";
    public static String fileSaveFolder = "apexstartup";
    private ListView lvConnectType;
    private ArrayList<String> types; //手机支持的连接方式
    private ConnectTypeAdapter adapter;
    private ProgressDialog progressDialog;
    private ArrayList<Adapter> wifiDatas = new ArrayList<>();
    private TextView tvWifiSelected;
    private TextView tvWifiStatus;
    private LinearLayout llWifiStatus;
    private Button btnReconnect;
    private Button btnWrite, btnRead;
    private Device mDevice;
    public CardListener mCardListener;
    private Card card;
    private List<CardFile> cardFileList;
    private CardFileReader reader = null;
    private Map<String, Long> totalAmountMap;
    private long cardContent;
    private CardFileReadListener mCardReadListener;
    private float currentPercent;
    private CardFileWriter writer = null;
    private CardFileWriteListener writeListener = null;
    private int readOrWrite;
    private int ACTION_READ = 0x01;
    private int ACTION_WRITE = 0x02;
    private EditText etCardName;
    private ArrayList<String> filePaths = new ArrayList<>();
    private ListView lvWrite;
    private WriteFilesAdapter writeFilesAdapter;
    private ReadFilesAdapter readFilesAdapter;
    private TextView tvWriteProgress;
    private TextView tvCardName, tvReadProgress;
    private TextView tvTotalLength;
    private int fileReadProgress;
    private ListView lvReadList;
    private ArrayList<ReadFile> readDatas = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
        getPhoneSupportConnectTypes();
        initViews();
        copyFiles();
    }

    private void bindViews() {
        lvConnectType = (ListView) findViewById(R.id.activity_main_lv_support);
        tvWifiSelected = (TextView) findViewById(R.id.activity_main_tv_wifi_selected);
        tvWifiStatus = (TextView) findViewById(R.id.activity_main_tv_wifi_status);
        llWifiStatus = (LinearLayout) findViewById(R.id.activity_main_ll_wifi_status);
        btnReconnect = (Button) findViewById(R.id.activity_main_btn_reconnect);
        btnRead = (Button) findViewById(R.id.activity_main_btn_read);
        btnWrite = (Button) findViewById(R.id.activity_main_btn_write);
        etCardName = (EditText) findViewById(R.id.activity_main_et_card_name);
        lvWrite = (ListView) findViewById(R.id.activity_main_lv_write_file);
        tvWriteProgress = (TextView) findViewById(R.id.activity_main_tv_write_progress);
        tvCardName = (TextView) findViewById(R.id.activity_main_tv_read_card_name);
        tvReadProgress = (TextView) findViewById(R.id.activity_main_tv_read_progress);
        tvTotalLength = (TextView) findViewById(R.id.activity_main_tv_total_length);
        lvReadList = (ListView) findViewById(R.id.activity_main_lv_read_file);
    }

    private void initViews() {
        adapter = new ConnectTypeAdapter(types);
        lvConnectType.setAdapter(adapter);
        lvConnectType.setOnItemClickListener(this);
        btnReconnect.setOnClickListener(this);
        btnWrite.setOnClickListener(this);
        btnRead.setOnClickListener(this);
        writeFilesAdapter = new WriteFilesAdapter(filePaths);
        lvWrite.setAdapter(writeFilesAdapter);
        readFilesAdapter = new ReadFilesAdapter(readDatas);
        lvReadList.setAdapter(readFilesAdapter);
        lvReadList.setOnItemClickListener(this);
    }

    private void getPhoneSupportConnectTypes() {
        types = new ArrayList<>();
        if (DeviceUtils.isSupportNfc(this)) {
            types.add(Device.TYPE_NFC);
        }
        if (DeviceUtils.isSupportWiFi(this)) {
            types.add(Device.TYPE_WIFI);
        }
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "NFC action-->" + getIntent().getAction());
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
            if (mDevice != null && mDevice.getType().equals(Device.TYPE_NFC))
                ((NFCDevice) mDevice).setIntent(getIntent());
        }
        setIntent(new Intent());
        super.onResume();
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.activity_main_lv_support:
                String selectType = types.get(i);
                DeviceManager.getInstance().setDeviceType(selectType);
                mDevice = DeviceManager.getInstance().getDevice();
                mDevice.initContext(MainActivity.this);
                adapter.setSelectPosition(i);
                makeToastShort("您选择使用" + selectType + "连接方式！");
                if (selectType.equals(Device.TYPE_WIFI)) {
                    btnRead.setEnabled(false);
                    btnWrite.setEnabled(false);
                    scanWifi();
                    llWifiStatus.setVisibility(View.VISIBLE);
                } else {
                    btnRead.setEnabled(true);
                    btnWrite.setEnabled(true);
                    tvWifiSelected.setText("");
                    tvWifiStatus.setText("");
                    llWifiStatus.setVisibility(View.GONE);
                }
                break;
            case R.id.activity_main_lv_read_file:
                setPreLoad(readDatas.get(i).getPath());
                break;
        }
    }

    /**
     * 下载过程中，可随机改变下载顺序
     *
     * @param path
     */
    private void setPreLoad(String path) {
        for (int i = 0; i < cardFileList.size(); i++) {
            CardFile cardFile = cardFileList.get(i);
            if (cardFile.getFile().getAbsolutePath().equals(path)) {
                if (reader != null) {
                    reader.read(cardFile);
                    break;
                }
            }
        }
    }

    /**
     * 若扫描不到Wifi 请检查位置权限是否开启
     * android 6.0 以上，扫描Wifi 需要开位置权限
     */
    private void scanWifi() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在扫描WiFi...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                Device device = DeviceManager.getInstance().getDevice();
                if (device instanceof AdapterDevice == false) return;
                AdapterDevice adevice = (AdapterDevice) device;
                adevice.setAdapterListener(adapterScanListener);
                try {
                    adevice.scanAdapter();
                } catch (AdapterException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();
    }

    private AdapterListener adapterScanListener = new AdapterListener() {

        @Override
        public void onScanResult(List<Adapter> list) {
            String wifiname = null;
            if (list.size() == 0) {
                handler2.sendEmptyMessage(0);
            } else {
                Message msg = new Message();
                msg.obj = list;
                msg.what = 1;
                handler2.sendMessage(msg);
                for (int i = 0; i < list.size(); i++) {
                    Adapter a = list.get(i);
                    wifiname = a.getName();
                    Log.i(TAG, "------->" + wifiname);
                }
            }
        }

        @Override
        public void onConnected(AdapterEvent adapterEvent) {
            Log.i(TAG, "Wifi已成功连接！");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWifiStatus.setText("成功连接");
                    btnReconnect.setVisibility(View.GONE);
                    btnRead.setEnabled(true);
                    btnWrite.setEnabled(true);
                }
            });
        }

        @Override
        public void onDisconnect(AdapterEvent adapterEvent) {
            Log.i(TAG, "Wifi已断开连接！");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWifiStatus.setText("Wifi已断开连接！");
                    btnReconnect.setVisibility(View.VISIBLE);
                    btnRead.setEnabled(false);
                    btnWrite.setEnabled(false);
                }
            });
        }

        @Override
        public void onException(AdapterEvent adapterEvent) {
            Log.i(TAG, "Wifi无法连接，请检查后重试！");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWifiStatus.setText("Wifi无法连接，请检查后重试！");
                    btnReconnect.setVisibility(View.VISIBLE);
                    btnRead.setEnabled(false);
                    btnWrite.setEnabled(false);
                }
            });
        }

    };

    private Handler handler2 = new Handler() {
        AdapterDevice device;
        WifiSelectDialog dialog;

        @Override
        public void handleMessage(Message msg) {
            if (progressDialog != null) progressDialog.dismiss();
            wifiDatas.clear();
            if (msg.what == 0) {
                Toast.makeText(MainActivity.this, "没有可用的WiFi信号...", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 1) {
                Device dv = DeviceManager.getInstance().getDevice();
                if (dv instanceof AdapterDevice == false) return;
                device = (AdapterDevice) (dv);
                final List<Adapter> adapterList = (List<Adapter>) msg.obj;
                if (dialog != null && dialog.isShowing()) {
                    dialog.updateData(adapterList);
                } else {
                    dialog = new WifiSelectDialog(MainActivity.this, R.style.MyDialogStyle, adapterList);
                    dialog.show();
                    dialog.setOnItemClickListener(new WifiSelectDialog.OnItemClickListener() {
                        @Override
                        public void onItemClick(Adapter wifiAdapter) {
                            try {
                                device.setAdapter(wifiAdapter);
                                tvWifiSelected.setText("您选择的WiFi信号:" + wifiAdapter.getName());
                                tvWifiStatus.setText("正在连接wifi...");
                            } catch (AdapterException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_main_btn_reconnect:
                Device device = DeviceManager.getInstance().getDevice();
                if (device instanceof AdapterDevice) {
                    if (((AdapterDevice) device).getAdapter() != null)
                        ((AdapterDevice) device).reconnect();
                    btnReconnect.setVisibility(View.GONE);
                    tvWifiStatus.setText("正在连接wifi...");
                }
                break;
            case R.id.activity_main_btn_read:
                if (mDevice == null) return;
                mDevice.unlock();
                mDevice.setMode(Device.MODE_READ_ONLY);
                readOrWrite = ACTION_READ;
                if (mCardListener != null)
                    mDevice.removeCardListener(mCardListener);
                mCardListener = new CardListenerImpl();
                mDevice.addCardListener(mCardListener);
                resetReadStatus();
                break;
            case R.id.activity_main_btn_write:
                if (mDevice == null) return;
                mDevice.unlock();
                mDevice.setMode(Device.MODE_WRITE_ONLY);
                readOrWrite = ACTION_WRITE;
                if (mCardListener != null)
                    mDevice.removeCardListener(mCardListener);
                mCardListener = new CardListenerImpl();
                mDevice.addCardListener(mCardListener);
                resetWriteStatus();
                break;
        }
    }

    private void resetReadStatus() {
        tvCardName.setText("请贴卡");
        tvReadProgress.setText("");
        lvWrite.setVisibility(View.GONE);
        lvReadList.setVisibility(View.VISIBLE);
        readDatas.clear();
        readFilesAdapter.notifyDataSetChanged();
        tvWriteProgress.setText("");
        tvTotalLength.setText("");
        tvTotalLength.setVisibility(View.VISIBLE);
    }

    private void resetWriteStatus() {
        tvWriteProgress.setText("请贴卡");
        lvWrite.setVisibility(View.VISIBLE);
        tvTotalLength.setVisibility(View.VISIBLE);
        tvTotalLength.setText("总长度：" + getfilesSize());
        tvCardName.setText("");
        lvReadList.setVisibility(View.GONE);
        tvReadProgress.setText("");
    }

    /**********************************
     * 卡片监听
     *******************************************/

    private class CardListenerImpl implements CardListener {
        @Override
        public void onCardChanged(CardEvent cardChangedEvent) {
            Log.d(TAG, "on card changed");
            card = cardChangedEvent.getNewCard();
            if (card != null) {
                if (readOrWrite == ACTION_READ) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvCardName.setText("卡名称：" + card.getName() + "\n写卡时间：" + StringUtils.formatDate(card.getCreatedTime(), "MM-dd HH:mm"));
                        }
                    });
                    try {
                        readFile();
                    } catch (UnauthorizedException e) {
                        e.printStackTrace();
                    } catch (LockException e) {
                        e.printStackTrace();
                    }
                } else if (readOrWrite == ACTION_WRITE) {
                    write();
                }
            }

        }

        @Override
        public void onCardNotApplicable(CardEvent cardChangedEvent) {
            //在读取文件，或者手动锁定某张卡的情况下，把另外一张不同的卡片靠近读卡范围，将会触发本事件方法。
            //alert提醒用户，当前卡不是正在读取的卡片，请更换为正确的正在读取的卡片，或者取消当前读取或播放进度。
            Log.d(TAG, "on cardNot applicable");
        }

        @Override
        public void onCardTimeout(CardEvent cardChangedEvent) {
            //在读取文件，或者手动锁定某张卡的情况下，如果卡片离开读取范围，超过指定的Timeout时间，将会触发本事件方法。
            //alert提醒用户，由于当前正在读取的卡片长时间离开读取范围，已经自动取消读取或播放过程。
            Log.d(TAG, "on card timeout");
        }

        @Override
        public void onCardAttached(CardEvent cardEvent) {
            Log.d(TAG, "--onCardConnected-->");

        }

        @Override
        public void onCardUnattached(CardEvent cardEvent) {
            Log.d(TAG, "--onCardDisconnect-->");
        }

        @Override
        public void onCardException(CardEvent cardEvent) {
            Log.d(TAG, "--onCardException-->");
        }
    }

    /********************************
     * 读卡
     ****************************************/


    private void readFile() throws UnauthorizedException, LockException {
        totalAmountMap = new HashMap<>();
        cardContent = card.getFileLength();
        if (card != null) {
            cardFileList = card.listFile();
            try {
                reader = mDevice.getCardFileReader(card, "");
            } catch (ModeException e) {
                e.printStackTrace();
            }
            if (cardFileList == null || cardFileList.size() == 0) return;
            for (int i = 0; i < cardFileList.size(); i++) {
                CardFile file = cardFileList.get(i);
                ReadFile readfile = new ReadFile();
                readfile.setPath(file.getFile().getAbsolutePath());
                readfile.setLength(file.getLength());
                if (file.isCached()) {
                    Log.i(TAG, "-----cached---------" + file.getFile().getAbsolutePath());
                    totalAmountMap.put(file.getFile().getAbsolutePath(), new File(file.getFile().getAbsolutePath()).length());
                    readfile.setProgress(100);
                }
                readDatas.add(readfile);
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                lvReadList.setVisibility(View.VISIBLE);
                readFilesAdapter.notifyDataSetChanged();
            }
        });
        if (!checkIsAllFileCached()) {
            if (mCardReadListener == null) mCardReadListener = new CardReadListenerImpl();
            if (reader != null) {
                reader.setCardFileReadListener(mCardReadListener);
                reader.read(cardFileList);
            }
        }
    }

    private class CardReadListenerImpl implements CardFileReadListener {
        @Override
        public void onReadStart(CardFileReadEvent cardReadEvent) {
            Log.d(TAG, "on read start");
        }

        @Override
        public void onReadProgress(final CardFileReadEvent cardReadEvent) {
            Log.d(TAG, "on read progress" + cardReadEvent.getData().length);
            totalAmountMap.put(cardReadEvent.getCardFile().getFile().getAbsolutePath(), (long) cardReadEvent.getTotalAmount());
            currentPercent = cardReadEvent.getCard().getFileAmount() * 100f / cardReadEvent.getCard().getFileLength();
            System.out.println("---onReadProgress -------prgoress-->" + currentPercent);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    fileReadProgress = cardReadEvent.getTotalAmount() * 100 / cardReadEvent.getTargetAmount();
                    updateDatas(cardReadEvent.getCardFile().getFile().getAbsolutePath(), fileReadProgress);
                    tvReadProgress.setText("读卡进度：" + (int) currentPercent + "%");
                }
            });
        }

        @Override
        public void onReadFinish(CardFileReadEvent cardReadEvent) {
            String fileName = cardReadEvent.getCardFile().getFile().getAbsolutePath();
            Log.d(TAG, "read finish:" + fileName);
            System.out.println("read finish:" + cardReadEvent.getCard().getFileLength() + "   " + cardReadEvent.getCard().getFileAmount());
            checkIsAllFileCached();
        }

        @Override
        public void onReadPause(CardFileReadEvent cardReadEvent) {
            Log.d(TAG, "on read pause");
        }

        @Override
        public void onReadResume(CardFileReadEvent cardReadEvent) {
            Log.d(TAG, "on read resume");
        }

        @Override
        public void onReadCancel(CardFileReadEvent cardReadEvent) {
            Log.d(TAG, "on read cancel");
            mDevice.unlock();
            reader.close();
        }

    }

    public void updateDatas(String path, float progress) {
        for (int i = 0; i < readDatas.size(); i++) {
            if (path.equals(readDatas.get(i).getPath())) {
                readDatas.get(i).setProgress(progress);
                break;
            }
        }
        readFilesAdapter.notifyDataSetChanged();
    }

    private boolean checkIsAllFileCached() {
        if (getGlobleTotalAmount() == cardContent) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "卡片已经读完...", Toast.LENGTH_SHORT).show();
                    tvReadProgress.setText("卡片已经读完");
                }
            });
            Log.d(TAG, "-------------read finished------------>");
            return true;
        }
        return false;
    }

    private long getGlobleTotalAmount() {
        long globleAmount = 0;
        for (Long amount : totalAmountMap.values()) {
            globleAmount += amount;
        }
        return globleAmount;
    }

    /********************************
     * 写卡
     ****************************************/

    private void write() {
        try {
            writer = mDevice.getCardFileWriter(card, "");
        } catch (UnauthorizedException e) {
            mDevice.removeCardListener(mCardListener);
            e.printStackTrace();
        } catch (LockException e) {
            e.printStackTrace();
        } catch (ModeException e) {
            e.printStackTrace();
        }
        String cardName = etCardName.getText().toString().trim();
        if (StringUtils.isEmpty(cardName))
            card.setName("纪念卡001");
        else card.setName(cardName);
        card.setType(Card.TYPE_GROWMEMO_CARD);
        try {
            if (writeListener == null) writeListener = new CardFileWriteListenerImpl();
            writer.write(getWriteFiles(), writeListener, false);
        } catch (PackFormatException e) {
            mDevice.removeCardListener(mCardListener);
            e.printStackTrace();
        } catch (ModeException e) {
            e.printStackTrace();
        }
    }

    class CardFileWriteListenerImpl implements CardFileWriteListener {
        @Override
        public void onWriteStart(CardFileWriteEvent event) {
            Log.d(TAG, "onWriteStart-->  target-->" + event.getTargetAmount() + "event.gettotal--->" + event.getTotalAmount());
            //handler.obtainMessage(WRITE_START).sendToTarget();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWriteProgress.setText("开始写卡...");
                }
            });
        }

        @Override
        public void onWriteProgress(final CardFileWriteEvent event) {
            Log.d(TAG, "onWriteProgress--> " + event.toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Card writeCard = event.getCard();
                    tvWriteProgress.setText("卡名称:" + writeCard.getName() + "\n当前进度：" + (int) (event.getTotalAmount() * 100f / event.getTargetAmount()) + "%");
                }
            });
        }

        @Override
        public void onWriteFinish(CardFileWriteEvent event) {
            Log.d(TAG, "onWriteFinish-->  " + event.toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWriteProgress.setText("写卡完成");
                }
            });
            mDevice.unlock();
            writer.close();
            mDevice.removeCardListener(mCardListener);
        }

        @Override
        public void onWritePause(CardFileWriteEvent event) {
            Log.d(TAG, "onWritePause-->  " + event.toString());
//            handler.sendEmptyMessage(WRITE_PAUSE);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWriteProgress.setText("卡片离开...");
                }
            });
            // writer.Pause();
        }

        @Override
        public void onWriteResume(CardFileWriteEvent event) {
            Log.d(TAG, "onWriteResume-->  " + event.toString());
//            handler.sendEmptyMessage(WRITE_RESUME);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvWriteProgress.setText("重新开始...");
                }
            });
        }

        @Override
        public void onWriteCancel(CardFileWriteEvent event) {
            Log.d(TAG, "onWriteCancel-->  " + event.toString());
            writer.close();
            mDevice.removeCardListener(mCardListener);
        }
    }

    /*******************************************************************************/
    private void copyFiles() {
        final String fileSavePath = getCacheDir().getAbsolutePath() + File.separator + fileSaveFolder + File.separator;
        Log.i(TAG, fileSavePath);
        FileManager.generateFolder(fileSavePath);
        new Thread() {
            @Override
            public void run() {

                filePaths.add(FileManager.copyRaw(R.raw.file_001, fileSavePath + "file_001.jpg", MainActivity.this));
                filePaths.add(FileManager.copyRaw(R.raw.file_002, fileSavePath + "file_002.jpg", MainActivity.this));
                filePaths.add(FileManager.copyRaw(R.raw.file_003, fileSavePath + "file_003.jpg", MainActivity.this));
                filePaths.add(FileManager.copyRaw(R.raw.file_004, fileSavePath + "file_004.jpg", MainActivity.this));
                filePaths.add(FileManager.copyRaw(R.raw.file_005, fileSavePath + "file_005.jpg", MainActivity.this));
                handler.sendEmptyMessage(1);
            }
        }.start();
    }

    private List<File> getWriteFiles() {
        List<File> list = new ArrayList<>();
        for (int i = 0; i < filePaths.size(); i++) {
            list.add(new File(filePaths.get(i)));
        }
        return list;
    }

    private String getfilesSize() {
        List<File> files = getWriteFiles();
        long l = 0;
        for (int i = 0; i < files.size(); i++) {
            l += files.get(i).length();
        }
        return StringUtils.generateFileSize(l);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            writeFilesAdapter.notifyDataSetChanged();
            super.handleMessage(msg);
        }
    };

}
